package com.atwei.mango.system.apiModel.response;

import com.alibaba.fastjson.JSON;
import com.atwei.mango.system.exception.ResponseEnum;
import lombok.Data;

import javax.servlet.ServletResponse;
import java.io.PrintWriter;

/**
 * @Classname ApiResponse
 * @Description 统一返回对象
 * @Date 2022/5/27 18:12
 * @Author liuwei
 */
@Data
public class ApiResponse<T> {

    private int code;
    private T data;
    private String msg;

    public ApiResponse(int code, T data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    public ApiResponse(ResponseEnum responseEnum, T data) {
        this.code = responseEnum.getCode();
        this.msg = responseEnum.getMsg();
        this.data = data;
    }

    public ApiResponse(ResponseEnum responseEnum) {
        this.code = responseEnum.getCode();
        this.msg = responseEnum.getMsg();
    }


    public static <T> ApiResponse<T> success(T data){
        return new ApiResponse<>(ResponseEnum.SUCCESS,data);
    }
    public static <T> ApiResponse<T> error(ResponseEnum responseEnum){
        return new ApiResponse<>(responseEnum);
    }

    public static <T> ApiResponse<T> info(ResponseEnum responseEnum,T data){
        return new ApiResponse<>(responseEnum,data);
    }


    public static void responseJson(ServletResponse response, Object data){
        PrintWriter out = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            out = response.getWriter();
            out.println(JSON.toJSONString(data));
            out.flush();
        } catch (Exception e) {
            System.out.println("Response输出Json异常：" + e);
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }



}
